package net.lshimokawa.ejemplos.springjms;

import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.Message;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;

/**
 * 
 * @author lshimokawa
 * 
 */
public class EchoJmsClient {
	private Logger logger = Logger.getLogger(EchoJmsClient.class);
	private JmsTemplate jmsTemplate;
	private String requestDestination;
	private String responseDestination;

	public String sendAndReceive(final String requestMessage) {
		final String correlationId = UUID.randomUUID().toString();
		logger.debug("EchoJmsClient enviando: " + requestMessage);
		jmsTemplate.convertAndSend(requestDestination, requestMessage,
				new CorrelationIdPostProcessor(correlationId));
		String responseMessage = (String) jmsTemplate
				.receiveSelectedAndConvert(responseDestination,
						"JMSCorrelationID='" + correlationId + "'");
		logger.debug("EchoJmsClient recibiendo: " + responseMessage);
		return responseMessage;
	}

	private class CorrelationIdPostProcessor implements MessagePostProcessor {
		private final String correlationId;

		public CorrelationIdPostProcessor(final String correlationId) {
			this.correlationId = correlationId;
		}

		@Override
		public Message postProcessMessage(final Message msg)
				throws JMSException {
			msg.setJMSCorrelationID(correlationId);
			return msg;
		}
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setRequestDestination(String destinationName) {
		this.requestDestination = destinationName;
	}

	public void setResponseDestination(String responseDestination) {
		this.responseDestination = responseDestination;
	}

}
